// pages/get/get.js
const db = wx.cloud.database(); //初始化数据库
import {
  getTimeNow
} from '../../utils/util.js';
Page({
  data: {
    a: '',
    tabList: ['全部', '我的订单', '我帮助的', '未完成'],
    tabNow: 0, //当前tab
    orderList: [],
    myOrder: [],
    rewardOrder: [],
    helpOrder: [],
    openid: '',
    canReceive: false,
    helpTotalNum: 0,
    helpTotalMoeny: 0,
    lookNumber: 0,
    userInfo: '',
    einputinfo: '', //输入框值
    tsjiedan: true,
    state: '',
    name: '',
    phoneNumber: '',
/*     avinfo:'',
    nameinfo:'',
    wx:'', */
  },
  selectTab(e) {
    const {
      id
    } = e.currentTarget.dataset;
    this.setData({
      tabNow: id,
    })
    if (id === 0) {
      this.onLoad();
      this.getPersonPower();
    } else if (id === 1) {
      this.getMyOrder();
    } else if (id === 2) {
      this.getMyHelpOrder();
    } else if (id === 3) {
      this.getRewardOrder();
      this.getPersonPower();
    }
    //console.log(res)
    /*     this.setData({
          tabNow: e.currentTarget.dataset.id
        }) */
  },
  /*   db.collection('order').get({
        success: (res) => {
            const { data } = res;
            data.forEach(item => {
                const {expectGender, expectTime, remark, size } = item.info;
                const info = `快递类型: ${size} -- 期望送达: ${expectTime} -- 性别限制: ${expectGender} -- 备注: ${remark}`;
                item.info = info;
            });
            this.setData({
                orderList: data,
            })
        }
    })   */

  onLoad: function (options) {
    wx.showLoading({
      title: '加载中',
    })
    // 过审核
    const that = this
    db.collection("a").get()
      .then(res => {
        console.log("11111111", res.data[0].a)
        that.setData({
          a: res.data[0].a,
        })
      })
    var user = wx.getStorageSync('key')
    //console.log('头像',wx.getStorageSync('key').avatarUrl)
    if (user) {
      this.setData({
        userInfo: user
      })
    }
 
    this.getPersonPower();
    this.getHelpTotalNum();
    // 按照时间 倒序 查询
    db.collection('order').orderBy('createTime', 'desc').get({
      success: (res) => {
        console.log("hh", res)
        const {
          data
        } = res;
        data.forEach(item => {
          item.info = this.formatInfo(item);
          item.stateColor = this.formatState(item.state);
        });
        this.setData({
          orderList: data,
          openid: wx.getStorageSync('openid')
        })
        //console.log("123456", res)
        wx.hideLoading();
      },
      fail: (res) => {
        wx.showToast({
          icon: 'none',
          title: '服务器异常~~~',
        })
        wx.hideLoading();
      }
    })
  },
  /* 我的订单 */
  /*   wx.cloud.callFunction({
      name: 'getopenID',
      success: (res) => {
        console.log(res.result.openid)
        db.collection('order').where({
          _openid: res.result.openid
        }).get({
          success: (res) => {
            console.log(res)
          
          }
        })
      }
    }) */

  // 获取我的订单信息
  getMyOrder() {
    wx.showLoading({
      title: '加载中',
    })
    wx.cloud.callFunction({
      name: 'getopenID',
      success: (res) => {
        console.log(res.result.openid)
        db.collection('order').orderBy('createTime', 'desc').where({
          _openid: res.result.openid
        }).get({
          success: (res) => {
            console.log("我", res)
            const {
              data
            } = res;
            data.forEach(item => {
              item.info = this.formatInfo(item);
              item.stateColor = this.formatState(item.state);
            });
            this.setData({
              myOrder: data,
            })
            /* 数据为空时 */
            if (res.data.length === 0) {
              wx.showToast({
                icon: 'none',
                title: '暂无数据',
              })
            }


            wx.hideLoading();
          }
        })
      }
    })
  },

  // 获取我帮助的订单信息 
  /*   getMyHelpOrder() {
      wx.showLoading({
        title: '加载中',
      })
      wx.cloud.callFunction({
        name: 'getopenID',
        success: (res) => {
          console.log(res.result.openid)
          db.collection('order').orderBy('createTime', 'desc').where({
            rewardOrder: res.result.openid
          }).get({
            success: (res) => {
              const {
                data
              } = res;
              data.forEach(item => {
                item.info = this.formatInfo(item);
                item.stateColor = this.formatState(item.state);

              });
              this.setData({
                helpOrder: data,
              })
              wx.hideLoading();
            }
          })
        }
      })
    }, */

  // 获取我帮助的订单信息 
  getMyHelpOrder() {
    wx.showLoading({
      title: '加载中',
    })
    db.collection('order').orderBy('createTime', 'desc').where({
      receivePerson: this.data.openid
    }).get({
      success: (res) => {
        const {
          data
        } = res;
        data.forEach(item => {
          item.info = this.formatInfo(item);
          item.stateColor = this.formatState(item.state);
        });
        this.setData({
          helpOrder: data,
        })
        wx.hideLoading();
      }
    })
  },

  // 获取 未完成 的订单信息
  getRewardOrder() {
    wx.showLoading({
      title: '加载中',
    })
    db.collection('order').orderBy('createTime', 'desc').where({
      state: '待帮助'
    }).get({
      success: (res) => {
        console.log(res.data.length)
        const {
          data
        } = res;
        data.forEach(item => {   
          item.info = this.formatInfo(item);
          item.stateColor = this.formatState(item.state);
        });
        this.setData({
          rewardOrder: data,
        })
        /* 数据为空时 */
        if (res.data.length === 0) {
          wx.showToast({
            icon: 'none',
            title: '暂无数据',
          })
        }
        wx.hideLoading();
      },
    })
  },

  toFinish(e) {
    wx.showLoading({
      title: '加载中',
    })
    const {
      item
    } = e.currentTarget.dataset;
    const {
      _id
    } = item;
    db.collection('order').doc(_id).update({
      data: {
        state: '已完成'
      },
      success: (res) => {
        this.getMyOrder();
        wx.hideLoading();
      }
    })
  },
  
  // 获取接单员信息 和 限制接单
  getPersonPower() {
    wx.cloud.callFunction({
      name: 'getopenID',
      success: (res) => {
        db.collection('orderReceive').where({
          _openid: res.result.openid,
          state: '通过'
        }).get({
          success: (res) => {
            console.log('接单员数据库：',res)
            this.setData({
              canReceive: !!res.data.length,
              name: res.data[0].name,
              phoneNumber: res.data[0].phoneNumber,
            })

          }
        })
      }
    })
    /*   db.collection('orderReceive').where({
        _openid: wx.getStorageSync('openid'),
        state: '通过'
      }).get({
        success: (res) => {
          console.log("111",res)
          this.setData({
            canReceive: !!res.data.length
          })
        }
      }) */
  },

  // 点击接单
  orderReceive(e) {
    wx.showLoading({
      title: '加载中.....',
    })   
    //console.log(this.data.canReceive)
   // const index = e.currentTarget.dataset.index
  // const imgdata = this.data.orderList[index]
    //const orderdata = this.data.orderList[index]
   // const _id = orderdata._id
    const userInfo = wx.getStorageSync('key');
    if (this.data.canReceive && userInfo) {
      //db.collection('order').doc(_id).get({
        //success(res) {
          //console.log(单,res)
          wx.setStorageSync('der', '1')
          const index = e.currentTarget.dataset.index
          const imgdata = this.data.orderList[index]
          const orderdata = this.data.orderList[index]
          const nowid = orderdata._id
          const openID = imgdata._openid
          const orderID = imgdata.orderid

          console.log('发给用户的 openid 为：',imgdata._openid)

            // 调用云函数 解决多人同时接单问题
            wx.cloud.callFunction({
              name:'getnow',
              data: {
                _id: nowid
              }
          }).then((res) => {
            console.log(res)
 
            if( res.result.data[0].state == '已帮助'  ) {
              wx.showToast({
                title: '已被抢单，请下拉刷新',
                icon: 'none'
              })
             return
            }else {
              const {
                item
              } = e.currentTarget.dataset;
              const {
                _id,
              } = item;
                // 调用云函数 推送订单被接信息 给用户
                wx.cloud.callFunction({
                  name: "send",
                  data: {
                    openid: openID,
                    orderID: orderID,
                    name: this.data.name,
                    phoneNumber: this.data.phoneNumber,
                    time: getTimeNow(),
                  },
                }) .then(res => {
                  console.log('推送消息发送成功：',res)
                  
                }).catch(error => {
                      console.log('推送消息发送失败：',error)
                })

              // 调用云函数 跳过权限 修改订单状态
              wx.cloud.callFunction({
                name: "updata",
                data: {
                  _id,
                  receivePerson: this.data.openid,
                  state: "已帮助"
                },
              }) .then(res => {
                if (this.data.tabNow === 0) {
                  this.onLoad();
                } else {
                  this.getRewardOrder();
                }
              })
            }
          })
      //  }
        this.onLoad();
    
      
      } else {
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: '抱歉 ！您还不是接单员或未登录, 请前往个人中心登录后申请成为接单员!'
      })
    } 
    wx.hideLoading()


  },





    // 点击接单
    helpreceive(e) {
      //console.log(this.data.canReceive)
     // const index = e.currentTarget.dataset.index
    // const imgdata = this.data.orderList[index]
      //const orderdata = this.data.orderList[index]
     // const _id = orderdata._id
      const userInfo = wx.getStorageSync('key');
      if (this.data.canReceive && userInfo) {
      wx.showLoading({
          title: '加载中',
        })  
        //db.collection('order').doc(_id).get({
          //success(res) {
            //console.log(单,res)
            const index = e.currentTarget.dataset.index
            const imgdata = this.data.rewardOrder[index]
            const orderdata = this.data.rewardOrder[index]
             const nowid = orderdata._id
             const openID = imgdata._openid
             const orderID = imgdata.orderid
           // console.log('111122',imgdata)
   
              wx.cloud.callFunction({
                name:'getnow',
                data: {
                  _id: nowid
                }
            }).then((res) => {
              if( res.result.data[0].state == '已帮助'  ) {
                wx.showToast({
                  title: '已被抢单，请下拉刷新',
                  icon: 'none'
                })
               return
              }else {
                const {
                  item
                } = e.currentTarget.dataset;
                const {
                  _id,
                } = item;

                                // 调用云函数 推送订单被接信息 给用户
                                wx.cloud.callFunction({
                                  name: "send",
                                  data: {
                                    openid: openID,
                                    orderID: orderID,
                                    name: this.data.name,
                                    phoneNumber: this.data.phoneNumber,
                                    time: getTimeNow(),
                
                                  },
                                }) .then(res => {
                                  console.log('推送消息发送成功：',res)
                                  
                                }).catch(error => {
                                      console.log('推送消息发送失败：',error)
                                })

                wx.cloud.callFunction({
                  name: "updata",
                  data: {
                    _id,
                    receivePerson: this.data.openid,
                    state: "已帮助"
                  },
                }) .then(res => {
                  console.log('修改为已帮助：',res)
                  if (this.data.tabNow === 0) {
                    this.onLoad();
                  } else {
                    this.getRewardOrder();
                  }
    
                })









              }
  
               
            })
  
  
        //  }
          this.onLoad();
      } 
      else {
        wx.showModal({
          title: '提示',
          showCancel: false,
          content: '抱歉 ！您还不是接单员或未登录, 请前往个人中心登录后申请成为接单员!'
        })
      } 
  
  
    },




  /*  const {
        item
      } = e.currentTarget.dataset;
      const {
        _id,
      } = item;
      wx.cloud.callFunction({
        name: "updata",
        data: {
          _id,
          receivePerson: this.data.openid,
          state: "已帮助"
        },
        success: (res) => {
          this.setData({
            tabNow: 0,
          })
          this.onLoad();
/*           if (this.data.tabNow === 0) {
            this.onLoad();
            this.onShow();
          } else {
            this.getRewardOrder();
          } */

        /* wx.hideLoading();
        },
      }) */
      //wx.hideLoading();

  formatInfo(orderInfo) {
    const {
      name,
      info,
    } = orderInfo;
    if (name === '快递代取') {
      const {
        expectGender,
        expectTime,
        remark,
        size
      } = info;
      return `快递类型--${size} , 期望送达--${expectTime} , 性别限制--${expectGender} , 备注--${remark}`;
    } else if (name === '打印服务') {
      const {
        colorPrint,
        pageNum,
        remark,
        twoSided
      } = info;
      return `页数: ${pageNum} -- 是否彩印: ${colorPrint ? '是' : '否'} -- 是否双面: ${twoSided ? '是' : '否'} -- 备注: ${remark}`;
    } else if (name === '校园跑腿') {
      const {
        beizhu,
      } = info;
      return `${beizhu} `;
    }
    else if (name === '代拿外卖') {
      const {
        beizhu,
      } = info;
      return `${beizhu} `;
    }
    else if (name === '食堂买饭') {
      const {
        beizhu,
      } = info;
      return `${beizhu} `;
    }
     else if (name === '代搬东西') {
      const {
        beizhu,
      } = info;
      /* return `帮助内容: ${beizhu} `; */
      return `${beizhu} `;
    } else if (name === '租借服务') {
      const {
        leaseItem,
        leaseTime,
        deliveryTime
      } = info;
      return `租借物品: ${leaseItem} -- 租借时长: ${leaseTime} -- 预计交货时间: ${deliveryTime}`;
    } else if (name === '游戏陪玩') {
      const {
        gameID,
        gameName,
        gameTime,
        remark
      } = info;
      return `游戏名称: ${gameName} -- 游戏时间or盘数: ${gameTime} -- 游戏ID: ${gameID} -- 备注信息: ${remark}`;
    } else if (name === '帮我送') {
      const {
        deliveryInfo
      } = info;
      return `送达地点: ${deliveryInfo}`;
    } else if (name === '代替服务') {
      const {
        helpContent
      } = info;
      return `${helpContent}`;
    } else if (name === '其他服务') {
      const {
        beizhu
      } = info;
      return `${beizhu}`;
    }
  },

  formatState(state) {
    if (state === '待帮助') {
      return 'top_right';
    } else if (state === '已帮助') {
      return 'top_right_help';
    } else if (state === '已完成') {
      return 'top_right_finish';
    }
  },


  /**
   * 页面上拉触底事件的处理函数 解决20条数据限制
   */
  onReachBottom: function () {
    wx.showLoading({
      title: '加载中',
    })
    let {
      orderList,
      myOrder,
      rewardOrder,
      helpOrder,
      tabNow,
      openid
    } = this.data;

    if (tabNow === 0) {
      db.collection('order').orderBy('createTime', 'desc').skip(orderList.length).get({
        success: (res) => {
          if (res.data.length) {
            res.data.forEach(item => {
              item.info = this.formatInfo(item);
              item.stateColor = this.formatState(item.state);
              orderList.push(item);
            })
            this.setData({
              orderList,
            })
          } else {
            wx.showToast({
              icon: 'none',
              title: '无更多信息',
            })
          }
          //wx.hideLoading();
        },
        fail: (error) => {
          wx.showToast({
            icon: 'none',
            title: '服务器出错...',
          })
          wx.hideLoading();
        }
      })
    } else if (tabNow === 1) {
      db.collection('order').orderBy('createTime', 'desc').skip(myOrder.length).where({
        _openid: openid
      }).get({
        success: (res) => {
          if (res.data.length) {
            const {
              data
            } = res;
            data.forEach(item => {
              item.info = this.formatInfo(item);
              item.stateColor = this.formatState(item.state);
              myOrder.push(item);
            });
            this.setData({
              myOrder,
            })
          } else {
            wx.showToast({
              icon: 'none',
              title: '无更多信息',
            })
          }
          //wx.hideLoading();
        }
      })
    } else if (tabNow === 2) {
      db.collection('order').orderBy('createTime', 'desc').skip(helpOrder.length).where({
        receivePerson: this.data.openid
      }).get({
        success: (res) => {
          if (res.data.length) {
            const {
              data
            } = res;
            data.forEach(item => {
              item.info = this.formatInfo(item);
              item.stateColor = this.formatState(item.state);
              helpOrder.push(item);
            });
            this.setData({
              helpOrder,
            })
          } else {
            wx.showToast({
              icon: 'none',
              title: '无更多信息',
            })
          }
          //wx.hideLoading();
        }
      })
    } else if (tabNow === 3) {
      db.collection('order').orderBy('createTime', 'desc').skip(rewardOrder.length).where({
        state: '待帮助'
      }).get({
        success: (res) => {
          if (res.data.length) {
            const {
              data
            } = res;
            data.forEach(item => {
              item.info = this.formatInfo(item);
              item.stateColor = this.formatState(item.state);
              rewardOrder.push(item);
            });
            this.setData({
              rewardOrder,
            })
          } else {
            wx.showToast({
              icon: 'none',
              title: '无更多信息',
            })
          }
          //wx.hideLoading();
        }
      })
    }
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.onLoad(),
      this.getRewardOrder()
    this.getMyOrder()

    setTimeout(() => {
      wx.showToast({
        icon: "none",
        title: '暂无更多数据',
      })
    }, 1000)
  },

  // 我帮助的订单单数总和
  getHelpTotalNum() {
    db.collection('order').where({
      receivePerson: wx.getStorageSync('openid'),
      state: '已完成'
    }).count({
      success: (res) => {
        //console.log(res);
        this.setData({
          helpTotalNum: res.total
        })
      }
    })
  },

  /* 跳转到订单详情页  调用云函数 突破 openID 限制 而修改 lookNumber 的值 达到用户浏览量 */
  to: function (res) {
    const index = res.currentTarget.dataset.index
    const imgdata = this.data.orderList[index]
    const orderdata = this.data.orderList[index]
    const _id = orderdata._id
    //console.log('imgdata',imgdata)

    wx.setStorageSync('_id', _id)


    //console.log("点击的Id为:", index)
    //console.log("浏览的id为：", orderdata._id)
    wx.setStorageSync('_id', orderdata._id)
    // 调用云函数 突破 openID的限制 而 修改lookNumber 实现用户浏览量  
    db.collection('order').doc(_id).get({
      success: (res) => {
        console.log("1234", res)
        const {
          data
        } = res;
        const {
          lookNumber
        } = data;
        this.setData({
          lookNumber
        })

        wx.cloud.callFunction({
          name: "lookNumber",
          data: {
            _id,
            lookNumber: lookNumber,
          },
          success: (res) => {
            this.onLoad()
          }
        })
      },
      fail: (res) => {
        showToast({
          icon: 'none',
          title: '显示内容失败'
        })
      }
    })

    const dataobj = {
      /* avinfo: this.data.avinfo,
      nameinfo: this.data.nameinfo,
      wx: this.data.wx, */
      // 性别限制
      expectGender: imgdata.expectGender,
      // 备注信息
      remark: imgdata.remark,
      // 期望送达
      expectTime: imgdata.expectTime,
      // 快递大小
      size: imgdata.size,

      receivePerson: imgdata.receivePerson,
      qujian: imgdata.qujian,
      lookNumber: imgdata.lookNumber,
      orderid: imgdata.orderid,
      addressS: imgdata.addressS,
      loselianxi: imgdata.loselianxi,
      QQ: imgdata.QQ,
      selectQQ: imgdata.selectQQ,
      Businessaddress: imgdata.Businessaddress,
      address: imgdata.address,
      createTime: imgdata.createTime,
      info: imgdata.info,
      money: imgdata.money,
      money: imgdata.money,
      name: imgdata.name,
      phonenumber: imgdata.phonenumber,
      receivePerson: imgdata.receivePerson,
      state: imgdata.state,
      stateColor: imgdata.stateColor,
      time: imgdata.time,
      userInfo: imgdata.userInfo,
      _id: imgdata._id,
      _openid: imgdata._openid,
    }

    /* 数据为空时 */
    const canReceive = this.data.canReceive;
    const userInfo = wx.getStorageSync('key');
    if (imgdata.state === '待帮助' && userInfo != null && userInfo != '' && canReceive) {
      setTimeout( function() {
        console.log('延时了')
        wx.showLoading({
          title: '请稍候...',
        })
        wx.navigateTo({
          url: '/pages/detail/detail',
          success: (res) => {
            res.eventChannel.emit('acceptDataFromOpenerPage', {
              data: dataobj
            })
          }
        })
      }, 1000);
wx.hideLoading()
     
    } else if (userInfo === null || userInfo === '') {
      console.log("14")
      wx.showToast({
        icon: "none",
        title: '抱歉！您还未登录 ！请先登录',
      })
    } else if (!canReceive) {
      console.log("15")
      wx.showToast({
        icon: "none",
        title: '抱歉！您还不是接单员 ！ 无法查看 ',
      })
    } else {
      wx.showToast({
        icon: "none",
        title: '抱歉！已被接单，无法跳转 ！',
      })
    }
  },

  // 我的订单跳转到详情页面
  myto(res) {
    const index = res.currentTarget.dataset.index
    const imgdata = this.data.myOrder[index]
    //const orderdata = this.data.orderList[index]
    const orderdata = this.data.myOrder[index]
    const _id = orderdata._id
    console.log('qqqq')
    wx.setStorageSync('_id', _id)
    console.log("点击我的订单1", index)
    console.log("点击后数据库的id", _id)

    // 调用云函数 突破 openID的限制 而 修改lookNumber 实现用户浏览量  
    db.collection('order').doc(_id).get({
      success: (res) => {
        console.log("我的浏览修改成功", res)
        const {
          data
        } = res;
        const {
          lookNumber
        } = data;
        this.setData({
          lookNumber
        })

        wx.cloud.callFunction({
          name: "lookNumber",
          data: {
            _id,
            lookNumber: lookNumber,
          },
          success: (res) => {
            this.onLoad()
            this.getMyOrder()
          }
        })
      },
      fail: (res) => {
        showToast({
          icon: 'none',
          title: '显示内容失败'
        })
      }
    })

    const dataobj = {
      /* avinfo: this.data.avinfo,
      nameinfo: this.data.nameinfo,
      wx: this.data.wx, */

      // 性别限制
      expectGender: imgdata.expectGender,
      // 备注信息
      remark: imgdata.remark,
      // 期望送达
      expectTime: imgdata.expectTime,
      // 快递大小
      size: imgdata.size,



      receivePerson: imgdata.receivePerson,
      qujian: imgdata.qujian,
      lookNumber: imgdata.lookNumber,
      orderid: imgdata.orderid,
      addressS: imgdata.addressS,
      loselianxi: imgdata.loselianxi,
      QQ: imgdata.QQ,
      selectQQ: imgdata.selectQQ,
      Businessaddress: imgdata.Businessaddress,
      address: imgdata.address,
      createTime: imgdata.createTime,
      info: imgdata.info,
      money: imgdata.money,
      money: imgdata.money,
      name: imgdata.name,
      phonenumber: imgdata.phonenumber,
      receivePerson: imgdata.receivePerson,
      state: imgdata.state,
      stateColor: imgdata.stateColor,
      time: imgdata.time,
      userInfo: imgdata.userInfo,
      _id: imgdata._id,
      _openid: imgdata._openid,
    }

    /* 数据为空时 */
    //const canReceive = this.data.canReceive;
    const userInfo = wx.getStorageSync('key');
    if (userInfo != null && userInfo != '') {
      setTimeout( function() {
        console.log('延时了')
        wx.showLoading({
          title: '请稍候...',
        })
      wx.navigateTo({
        url: '/pages/detail/detail',
        success: (res) => {
          res.eventChannel.emit('acceptDataFromOpenerPage', {
            data: dataobj
          })
        }
      })
    }, 1000);
wx.hideLoading()
    } else if (userInfo === null || userInfo === '') {
      wx.showToast({
        icon: "none",
        title: '抱歉！您还未登录 ！请先登录',
      })
    }



  },

  // 我帮助的订单 跳转到详情页面
  myto1(res) {
    const index = res.currentTarget.dataset.index
    const imgdata = this.data.helpOrder[index]
   // const orderdata = this.data.orderList[index]
    const orderdata = this.data.helpOrder[index]
    const _id = orderdata._id
    console.log('-------')
    wx.setStorageSync('_id', _id)

    console.log("点击我的订单1", index)
    console.log("点击后数据库的id", _id)

    // 调用云函数 突破 openID的限制 而 修改lookNumber 实现用户浏览量  
    db.collection('order').doc(_id).get({
      success: (res) => {
        console.log("我的浏览修改成功", res)
        const {
          data
        } = res;
        const {
          lookNumber
        } = data;
        this.setData({
          lookNumber
        })

        wx.cloud.callFunction({
          name: "lookNumber",
          data: {
            _id,
            lookNumber: lookNumber,
          },
          success: (res) => {
            this.onLoad()
            this.getMyOrder()
          }
        })
      },
      fail: (res) => {
        showToast({
          icon: 'none',
          title: '显示内容失败'
        })
      }
    })

    const dataobj = {
     /*  avinfo: this.data.avinfo,
      nameinfo: this.data.nameinfo,
      wx: this.data.wx, */

      // 性别限制
      expectGender: imgdata.expectGender,
      // 备注信息
      remark: imgdata.remark,
      // 期望送达
      expectTime: imgdata.expectTime,
      // 快递大小
      size: imgdata.size,

      receivePerson: imgdata.receivePerson,
      qujian: imgdata.qujian,
      lookNumber: imgdata.lookNumber,
      orderid: imgdata.orderid,
      addressS: imgdata.addressS,
      loselianxi: imgdata.loselianxi,
      QQ: imgdata.QQ,
      selectQQ: imgdata.selectQQ,
      Businessaddress: imgdata.Businessaddress,
      address: imgdata.address,
      createTime: imgdata.createTime,
      info: imgdata.info,
      money: imgdata.money,
      money: imgdata.money,
      name: imgdata.name,
      phonenumber: imgdata.phonenumber,
      receivePerson: imgdata.receivePerson,
      state: imgdata.state,
      stateColor: imgdata.stateColor,
      time: imgdata.time,
      userInfo: imgdata.userInfo,
      _id: imgdata._id,
      _openid: imgdata._openid,
    }

    /* 数据为空时 */
    //const canReceive = this.data.canReceive;
    const userInfo = wx.getStorageSync('key');
    if (userInfo != null && userInfo != '' && imgdata.state != '已完成') {
      setTimeout( function() {
        console.log('延时了')
        wx.showLoading({
          title: '请稍候...',
        })
      wx.navigateTo({
        url: '/pages/detail/detail',
        success: (res) => {
          res.eventChannel.emit('acceptDataFromOpenerPage', {
            data: dataobj
          })
        }
      })
    },2000);
wx.hideLoading()
    } else if (userInfo === null || userInfo === '') {
      wx.showToast({
        icon: "none",
        title: '抱歉！您还未登录 ！请先登录',
        duration: 2800,  
      })
    } else if (imgdata.state = '已完成') {
      wx.showToast({
        icon: "none",
        title: '订单已完成，无权访问，有疑问可私信管理',
        duration: 1000,  
      })
    }
  },

  // 我帮助的订单 跳转到详情页面
  myto2(res) {
    const index = res.currentTarget.dataset.index
    const imgdata = this.data.rewardOrder[index]
    // const orderdata = this.data.orderList[index]
    const orderdata = this.data.rewardOrder[index]
    const _id = orderdata._id
    console.log('-------')
    wx.setStorageSync('_id', _id)

    console.log("点击我的订单1", index)
    console.log("点击后数据库的id", _id)

    // 调用云函数 突破 openID的限制 而 修改lookNumber 实现用户浏览量  
    db.collection('order').doc(_id).get({
      success: (res) => {
        console.log("我的浏览修改成功", res)
        const {
          data
        } = res;
        const {
          lookNumber
        } = data;
        this.setData({
          lookNumber
        })

        wx.cloud.callFunction({
          name: "lookNumber",
          data: {
            _id,
            lookNumber: lookNumber,
          },
          success: (res) => {
            this.onLoad()
            this.getMyOrder()
          }
        })
      },
      fail: (res) => {
        showToast({
          icon: 'none',
          title: '显示内容失败'
        })
      }
    })

    const dataobj = {
      /*  avinfo: this.data.avinfo,
      nameinfo: this.data.nameinfo,
      wx: this.data.wx, */

      // 性别限制
      expectGender: imgdata.expectGender,
      // 备注信息
      remark: imgdata.remark,
      // 期望送达
      expectTime: imgdata.expectTime,
      // 快递大小
      size: imgdata.size,

      receivePerson: imgdata.receivePerson,
      qujian: imgdata.qujian,
      lookNumber: imgdata.lookNumber,
      orderid: imgdata.orderid,
      addressS: imgdata.addressS,
      loselianxi: imgdata.loselianxi,
      QQ: imgdata.QQ,
      selectQQ: imgdata.selectQQ,
      Businessaddress: imgdata.Businessaddress,
      address: imgdata.address,
      createTime: imgdata.createTime,
      info: imgdata.info,
      money: imgdata.money,
      money: imgdata.money,
      name: imgdata.name,
      phonenumber: imgdata.phonenumber,
      receivePerson: imgdata.receivePerson,
      state: imgdata.state,
      stateColor: imgdata.stateColor,
      time: imgdata.time,
      userInfo: imgdata.userInfo,
      _id: imgdata._id,
      _openid: imgdata._openid,
    }

    /* 数据为空时 */
    //const canReceive = this.data.canReceive;
    const userInfo = wx.getStorageSync('key');
    if (userInfo != null && userInfo != '' && imgdata.state != '已完成') {
      setTimeout( function() {
        console.log('延时了')
        wx.showLoading({
          title: '请稍候...',
        })
      wx.navigateTo({
        url: '/pages/detail/detail',
        success: (res) => {
          res.eventChannel.emit('acceptDataFromOpenerPage', {
            data: dataobj
          })
        }
      })
    },1000);
wx.hideLoading()
    } else if (userInfo === null || userInfo === '') {
      wx.showToast({
        icon: "none",
        title: '抱歉！您还未登录 ！请先登录',
        duration: 2800,  
      })
    } else if (imgdata.state = '已完成') {
      wx.showToast({
        icon: "none",
        title: '订单已完成，无权访问，有疑问可私信管理',
        duration: 1000,  
      })
    }
  },



  /* 删除 */
  delete(res) {
    const that = this;
    const index = res.currentTarget.dataset.index
    const orderdata = this.data.myOrder[index]
    console.log("删除的id为：", index)
    console.log("删除的id为：", orderdata._id)

    db.collection('order').doc(orderdata._id).get({
      success(res) {
        console.log(12346,res)
        if(res.data.state ==  '已完成' || res.data.state ==  '已帮助') {
          wx.showToast({
            title: '已被接单，无法删除！',
            icon:"none"
          })
        }else{
          wx.showModal({
            title: '提示',
            content: '您确定要它删除吗？删除后数据不可恢复 ！',
            confirmColor: '#00FF7F',
            cancelColor: '#FF4040',
            success: res => {
              if (res.confirm) {
                
                db.collection('order').doc(orderdata._id) 
                .remove({
                  success: res => {
                    wx.showToast({
                      title: '删除成功',
                      duration: 2000
                    });
                    that.getMyOrder();
                  },
                  fail: res => {
                    wx.showToast({
                      icon: "none",
                      title: '抱歉!似乎出了点小问题^-^',
                    })
                  }
                })
                //this.getMyOrder();
              }  
            }
          })

        }
      }
    })






  },

  // 未完成 跳转
  weiwanchengto() {
    wx.showToast({
      title: '不可跳转详情页,仅接单',
      icon: "none",
      duration: 2000,
    })
  },
  // 
  BtnClick(){
    wx.showToast({
      title: '出错啦~~~',
      icon:"error"
    })
  },
    /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (typeof this.getTabBar === 'function' &&
    this.getTabBar()) {
    this.getTabBar().setData({
      selected: 1
    })
  }
  },




})

/*   wx.showModal({
    title: '提示',
    content: '您确定要它删除吗？删除后数据不可恢复 ！',
    confirmColor: '#00FF7F',
    cancelColor: '#FF4040',
    success: res => {
      if (res.confirm) {
        db.collection('order').doc(orderdata._id).remove({
          success: res => {
            wx.showToast({
              title: '删除成功',
            });
            this.getMyOrder();
          },
          fail: res => {
            wx.showToast({
              icon: "none",
              title: '抱歉!似乎出了点小问题^-^',
            })
          }

        })
      } else {
        console.log('用户点击取消')
      }
    },

  })  */


/*   Component({
    pageLifetimes: {
      show() {
        if (typeof this.getTabBar === 'function' &&
          this.getTabBar()) {
          this.getTabBar().setData({
            selected: 1
          })
        }
      }
    },
  })
 */



